#include<iostream>

#include<stdio.h>

#include<string>

#include <sys/types.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#include<unistd.h>

#include<string.h>

#define SIZE 1024

enum
{
    SOCKETERR = 1,
    BINDERR,
    ARGCERR
};

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        std::cout << "3 wrods! error" << std::endl;
        exit(ARGCERR);
    }

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        perror("socket");
        exit(SOCKETERR);
    }

    sockaddr_in in;
    bzero(&in, sizeof(in));

    uint16_t serverport = std::stoi(argv[2]);
    in.sin_addr.s_addr = inet_addr(argv[1]);
    in.sin_family = AF_INET;
    in.sin_port = htons(serverport);

    char buffer[SIZE] = {0};
    std::string message;
    while(1)
    {
        std::cout << "please enter# ";
        std::getline(std::cin, message);
        if(sendto(sockfd, message.c_str(), message.size(), 0, (sockaddr*)&in, sizeof(in)) < 0)
        {
            perror("sendto");
        }

        sockaddr_in temp;
        socklen_t len = sizeof(temp);

        ssize_t ret = recvfrom(sockfd, buffer, SIZE, 0, (sockaddr*)&temp, &len);

        buffer[ret] = 0;

        if(ret > 0) std::cout << "get a message back：" << buffer << std::endl;
    }

    close(sockfd);
    return 0;
}